package com.example.demo.controller;

import com.example.demo.common.Constant;
import com.example.demo.common.PasswordSalt;
import com.example.demo.common.Result;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注册功能
     */
    @RequestMapping("/reg") //注册页的请求处理
    public Object reg(String username,String password) {
        //1.非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail(-1, "非法的参数请求");
        }

        //2.添加操作
        int result = userService.add(username,
                PasswordSalt.encrypt(password));
        if (result == 1) {
            return Result.success("数据添加成功", 1);
        } else {
            return Result.fail(-1, "添加失败");
        }
    }

    /**
     * 登陆功能
     */
    @RequestMapping("/login")
    public int login(HttpServletRequest request, String username, String password) {
        //1.非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return 0;
        }
        //2.查询数据库
        UserInfo userInfo = userService.getUserByName(username);
        if (userInfo == null || userInfo.getId() <= 0) {
            //登陆失败
            return 0;
        } else {
            boolean result=PasswordSalt.decrypt(password,userInfo.getPassword());
            if(result) {
                HttpSession session = request.getSession();
                session.setAttribute(Constant.SESSION_USERINFO_KEY, userInfo);
                return 1;
            }
        }
        return -1;
    }

    /**
     * 退出登陆
     */
    @RequestMapping("/exit")
    public boolean exit(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constant.SESSION_USERINFO_KEY) != null) {
            //session有值,移除信息
            session.removeAttribute(Constant.SESSION_USERINFO_KEY);
        }
        return true;
    }

    /**
     * 查询用户信息
     */
    @RequestMapping("/myinfo") //获取用户信息
    public UserInfo myInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constant.SESSION_USERINFO_KEY) != null) {
            //用户正常登陆状态
            UserInfo userInfo = (UserInfo) session.getAttribute(Constant.SESSION_USERINFO_KEY);
            return userInfo;
        }
        return null;
    }
}
